<?php


namespace App\Services\Pay\Google;


use App\Exception\MessageException;
use App\Model\ThirdToken;
use App\Utils\LoggerUtil;
use App\Utils\RedisClient;
use App\Utils\ToolUtil;


class GooglePay
{
    private static string $ClientID = "671800392511-k5h3iq23jiotvse4qmbpbjsri8j3av0v.apps.googleusercontent.com";
    private static string $ClientSecret = "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";

    /**
     * 使用该方法获取 $freshToken
     * @return bool|mixed|Redis|string
     */
    public function getRefreshToken()
    {
        $redis = RedisClient::getInstance();
        $refreshToken = $redis->get('googlepay_refresh_token');
        if (empty($refreshToken)) {
            // $thirdTokenModel = new ThirdTokenModel();
            // $sql = "SELECT refresh_token FROM tb_third_token WHERE type=1 ORDER BY ctime DESC limit 1";
            // $refreshToken = $thirdTokenModel->findOneField($sql, 'refresh_token');
            $refreshToken = ThirdToken::query()->where('type', 1)->orderByDesc('ctime')->value('refresh_token') ?? '';
            $redis->set('googlepay_refresh_token', $refreshToken);
        }
        return $refreshToken;

    }


    /**
     * Note - 验证google内购订单
     * DateTime 2024/8/23 15:58
     * User Admin
     * @param $productId -google内购的商品id
     * @param $orderToken -google支付的idtoken
     * @param $packageName -APP包名
     * @return false|mixed
     */
    public function verifyOrder($productId, $orderToken, $packageName)
    {
        $accessToken = $this->getAccessToken();
        if ($accessToken) {
            $url = 'https://www.googleapis.com/androidpublisher/v3/applications/' . $packageName . '/purchases/products/' . $productId . '/tokens/' . $orderToken . '?access_token=' . $accessToken;
            $result = ToolUtil::api_curl($url, null);
            $contents = json_decode($result, true);
            if (!empty($contents)) {
                if (isset($contents['error'])) {
                    LoggerUtil::write("google_pay", $contents, "GooglePayCurlErrorResult");
                }
                return $contents;
                // if ($contents['consumptionState'] === 0 && $contents['purchaseState'] === 0) {
                //     // 消耗订单
                //     $this->consume($productId, $orderToken, $packageName, $accessToken, $contents['developerPayload']);
                //     return true;
                // } elseif ($contents['consumptionState'] === 1 && $contents['purchaseState'] === 0) {
                //     // 已经消耗了
                //     return true;
                // } else {
                //     //訂單驗證失敗
                //     Tool::log("pay.txt", '订单状态有误', "GooglePayNotifyCurlResult");
                // }
            }
            return false;
        } else {
            LoggerUtil::write("google_pay", 'TOKEN丟失', "GooglePayCurlError");
            return false;
        }
    }

    /**
     * google token
     *
     * @return array|bool
     */
    public function getAccessToken()
    {
        try {
            $redis = RedisClient::getInstance();
            $cacheKey = 'gl:access_token';
            if ($redis->exists($cacheKey)) {
                return $redis->get($cacheKey);
            }
            $url = 'https://accounts.google.com/o/oauth2/token';
            $data['refresh_token'] = $this->getRefreshToken();
            $data['client_id'] = self::$ClientID;
            $data['client_secret'] = self::$ClientSecret;
            $data['grant_type'] = 'refresh_token';
            $response = ToolUtil::api_curl($url, $data);
            LoggerUtil::write("google_pay", $response, "GooglePayAccessTokenCurlResult");
            $result = json_decode($response, true);

            if ($result) {
                if (isset($result['access_token'])) {
                    $redis->set($cacheKey, $result['access_token'], 3600);
                    return $result['access_token'];
                }
            }
            return false;
        } catch (\Exception $e) {
            LoggerUtil::write("google_pay", $e->getMessage(), "error");
            throw new MessageException('鉴权失败');
            // dd($e->getMessage());
        }

    }


    /**
     * 非消耗型商品购买交易
     *
     * @param $productId
     * @param $token -客户端上传的token
     * @param $packageName
     * @param $accessToken
     * @param $developerPayload
     */
    private function acknowledge($productId, $token, $packageName, $accessToken, $developerPayload)
    {
        $url = 'https://www.googleapis.com/androidpublisher/v3/applications/' . $packageName . '/purchases/products/' . $productId . '/tokens/' . $token . ':acknowledge?access_token=' . $accessToken;
        $post_data['developerPayload'] = $developerPayload;
        $result = ToolUtil::api_curl($url, $post_data);
        LoggerUtil::write("google_pay", $result, "GooglePayAcknowledge");

    }

    /**
     * 消耗型商品，将商品标记为已消耗
     *
     * @param $productId
     * @param $token //客户端上传的token
     * @param $packageName
     * @param $developerPayload
     */
    public function consume($productId, $token, $packageName, $developerPayload)
    {
        $accessToken = $this->getAccessToken();
        $url = 'https://www.googleapis.com/androidpublisher/v3/applications/' . $packageName . '/purchases/products/' . $productId . '/tokens/' . $token . ':consume?access_token=' . $accessToken;
        $post_data['developerPayload'] = $developerPayload;
        $result = ToolUtil::api_curl($url, $post_data);
        LoggerUtil::write("google_pay", $result, "GooglePayConsume");
        $contents = json_decode($result, true);
        if (!empty($contents)) {
            if (isset($contents['error'])) {
                LoggerUtil::write("google_pay", $contents, "GooglePayConsumeError");
                return false;
            }
        }
        return true;

    }


}